package com.azkj.album.utils;

import static android.graphics.BitmapFactory.decodeStream;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import androidx.core.content.FileProvider;

import com.azkj.album.MyApplication;
import com.azkj.album.network.utils.ToastUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ImageUtils {


    /*
     * 保存文件，文件名为当前日期
     */
    public static boolean saveBitmap(Context context, Bitmap bitmap, SaveCallBack callBack) {
        String fileName;
        File file;
        String brand = Build.BRAND;
        String bitName = "_save_" + System.currentTimeMillis() + ".jpg";
        if (brand.equals("xiaomi")) { // 小米手机brand.equals("xiaomi")
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else if (brand.equalsIgnoreCase("Huawei")) {
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            saveSignImage(context, bitName, bitmap, callBack);
            return true;
        } else {
            Log.d("saveBitmap brand", "" + brand);
            file = new File(fileName);
        }
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
                // 插入图库
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //保存失败 删除该图
            file.delete();
            if (callBack != null) {
                callBack.saveCallBack(-1, "保存失败，请重试");
            }
//            ToastUtils.showThreadToast("保存失败，请重试");
            return false;
        }
        if (callBack != null) {
            callBack.saveCallBack(0, "保存成功");
        }
//        ToastUtils.showThreadToast("保存成功");
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        return true;
    }


    //将文件保存到公共的媒体文件夹
//这里的filepath不是绝对路径，而是某个媒体文件夹下的子路径，和沙盒子文件夹类似
//这里的filename单纯的指文件名，不包含路径
    public static void saveSignImage(Context context, String fileName, Bitmap bitmap, SaveCallBack callBack) {
        try {
            //设置保存参数到ContentValues中
            ContentValues contentValues = new ContentValues();
            //设置文件名
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
            //RELATIVE_PATH是相对路径不是绝对路径
            //DCIM是系统文件夹，关于系统文件夹可以到系统自带的文件管理器中查看，不可以写没存在的名字
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/");
            //contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Music/signImage");

            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
            //执行insert操作，向系统文件夹中添加文件
            //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            if (uri != null) {
                //若生成了uri，则表示该文件添加成功
                //使用流将内容写入该uri中即可
                OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
                if (outputStream != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                    if (callBack != null) {
                        callBack.saveCallBack(0, "保存成功");
                    }
//                    ToastUtils.showThreadToast("保存成功");
                }
            }
        } catch (Exception e) {
            if (callBack != null) {
                callBack.saveCallBack(-1, "保存失败，请重试");
            }
//            ToastUtils.showThreadToast("保存失败，请重试");
        }
    }

    public interface SaveCallBack {
        void saveCallBack(int status, String msg);
    }

    public static Bitmap createBitmapFromView(View viewGroup) {

        //重新调用WebView的measure方法测量实际View的大小（将测量模式设置为UNSPECIFIED模式也就是需要多大就可以获得多大的空间）
        viewGroup.measure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //调用layout方法设置布局（使用新测量的大小）
        viewGroup.layout(0, 0, viewGroup.getMeasuredWidth(), viewGroup.getMeasuredHeight());
        //开启WebView的缓存(当开启这个开关后下次调用getDrawingCache()方法的时候会把view绘制到一个bitmap上)
        viewGroup.setDrawingCacheEnabled(true);
        //强制绘制缓存（必须在setDrawingCacheEnabled(true)之后才能调用，否者需要手动调用destroyDrawingCache()清楚缓存）
        viewGroup.buildDrawingCache();
        //根据测量结果创建一个大小一样的bitmap
        Bitmap picture = Bitmap.createBitmap(viewGroup.getMeasuredWidth(),
                viewGroup.getMeasuredHeight(), Bitmap.Config.RGB_565);
        //已picture为背景创建一个画布
        Canvas canvas = new Canvas(picture); // 画布的宽高和 WebView 的网页保持一致
        Paint paint = new Paint();
        //设置画笔的定点位置，也就是左上角
        canvas.drawBitmap(picture, 0, viewGroup.getMeasuredHeight(), paint);
        //将webview绘制在刚才创建的画板上
        viewGroup.draw(canvas);
        return picture;
    }


    public static Bitmap getWxBitmap(Bitmap bm) {
        int width = bm.getWidth();
        int height = bm.getHeight();

        float scale = (1024f * 8 * 400) / (width * height);
        if (scale > 1) {
            return bm;
        }
        return setImgSize(bm, scale);
    }

    //宽高同比例缩放 scale
    public static Bitmap setImgSize(Bitmap bm, float scale) {
        // 取得想要缩放的matrix参数.
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        // 得到新的图片.
        Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        return bitmap;


    }

    public static Uri getUri(Bitmap bitmap) {
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(MyApplication.getCurrentActivity().getContentResolver(),
                bitmap, "image_" + System.currentTimeMillis(), "desc_" + System.currentTimeMillis()));
        return uri;
    }

    public static Uri bitmap2uri(Context c, Bitmap b) {//c.getCacheDir()
        File file0 = new File(c.getExternalCacheDir() +
                File.separator + "img");

        try {
            if (!file0.exists()) {
                file0.getParentFile().mkdirs();
                file0.mkdirs();
            }

            File file1 = new File(file0, ".nomedia");
            if (!file1.exists()) {
                file1.createNewFile();
            }
            File file = new File(file0, System.currentTimeMillis() + "_share.jpg");
            if (!file.exists()) {
                file.createNewFile();
            }

            OutputStream os = new FileOutputStream(file);
            b.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.close();

            Uri uri;
            if (Utils.isHarmonyOs() && Utils.getHarmonyVersion().startsWith("2")) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                uri = c.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                uri = Uri.fromFile(file);
            } else if ("VIVO".equalsIgnoreCase(Build.BRAND)) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
                uri = c.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            } else {
                uri = FileProvider.getUriForFile(c, MyProvider.getProvider(), file);
            }

            return uri;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Uri getImgContentUri(Context context, File imagefile) {


        String filepath = imagefile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filepath}, null);
        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseuri = uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseuri, "" + id);
            }
            cursor.close();
        }
        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filepath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }
        return uri;
    }

    public static Uri getImgContentUri2(Context context, File imagefile) {
        Uri contentUri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            contentUri = getFileUri(context, imagefile);
        } else {
            contentUri = Uri.fromFile(imagefile);

        }
        return contentUri;
    }


    public static Uri getFileUri(Context context, File file) {

        if (context == null) {
            return null;
        }

        if (file == null || !file.exists()) {
            return null;
        }

        Uri uri = null;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            uri = getImageContentUri(context, file);
        }

        if (uri == null) {
            uri = forceGetFileUri(file);
        }
        return uri;
    }




    private static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }

    private static Uri getVideoContentUri(Context context, File videoFile) {
        Uri uri = null;
        String filePath = videoFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Video.Media._ID}, MediaStore.Video.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/video/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Video.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }


    private static Uri getAudioContentUri(Context context, File audioFile) {
        Uri uri = null;
        String filePath = audioFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/audio/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }
        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Audio.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }

    private static Uri forceGetFileUri(File shareFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                @SuppressLint("PrivateApi")
                Method rMethod = StrictMode.class.getDeclaredMethod("disableDeathOnFileUriExposure");
                rMethod.invoke(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return Uri.parse("file://" + shareFile.getAbsolutePath());
    }


    public static void getImage(final String path, final HttpCallBackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageUrl = null;
                try {
                    imageUrl = new URL(path);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = decodeStream(is);
                    if (listener != null) {
                        listener.onFinish(bitmap);
                    }
                    is.close();
                } catch (IOException e) {
                    if (listener != null) {
                        listener.onError();
                    }
                    e.printStackTrace();
                }
            }

        }).start();

    }

    public interface HttpCallBackListener{
        void onFinish(Bitmap bitmap);
        void onFinish(String path, int position);
        void onError();
    }

    public static void downloadImgUrl(String downLoadUrl, String fileName, int position, HttpCallBackListener listener) {
        File folder = new File(MyApplication.getApplication().getExternalFilesDir(null) + "/shareData");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File imageFile = new File(folder.getPath() + File.separator + fileName + ".png");

        if (imageFile.exists()) {
            imageFile.delete();
            try {
                imageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        DownLoadApkUtils.download(downLoadUrl, imageFile, new DownLoadApkUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                if (listener!=null){
                    listener.onFinish(imageFile.getAbsolutePath(), position);

                }
            }

            @Override
            public void onDownloading(float progress) {


            }

            @Override
            public void onDownloadFailed(String msg) {
                listener.onError();

            }
        });
    }

    public static void downloadImgUrl(String downLoadUrl, String fileName,HttpCallBackListener listener) {
        downloadImgUrl(downLoadUrl, fileName, -1, listener);
    }

    /**
     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
     * @param bitmap
     * @param maxkb
     * @return
     */
    public static byte[] bmpToByteArray(Bitmap bitmap, int maxkb){
        Bitmap bm = Bitmap.createScaledBitmap(bitmap,100,100,true);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int options = 100;
        bm.compress(Bitmap.CompressFormat.PNG, options, output);

        while (output.toByteArray().length/1024 > maxkb) {
            output.reset(); //清空output
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, output); //这里压缩options%，把压缩后的数据存放到output中
            options -= 10;
        }
        return output.toByteArray();
    }

}